package mongodb.homework.week.three.one;

import java.net.UnknownHostException;
import java.util.List;
import java.util.TreeSet;

import org.apache.commons.collections.CollectionUtils;

import util.DBUtil;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

public class Question7 {

	/**
	 * @param args
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException {
		TreeSet<Integer> imageIdsInAlbums = new TreeSet<Integer>();
		DBCollection albums = DBUtil.getCollection("finalExam", "albums");

		DBObject query = new BasicDBObject();
		DBObject projection = new BasicDBObject("_id", 0).append("images", 1);
		DBCursor albumList = albums.find(query, projection);
		for (DBObject album : albumList) {
			BasicDBList dbList = (BasicDBList)album.get("images");
			for (Object id : dbList) {
				imageIdsInAlbums.add((Integer)id);
			}
		}
		
		TreeSet<Integer> imageSuperSet = new TreeSet<Integer>();
		DBCollection images = DBUtil.getCollection("finalExam", "images");
		projection = new BasicDBObject("height", 0).append("width", 0).append("tags", 0);
		DBCursor imageList = images.find(query, projection);
		for (DBObject dbObject : imageList) {
			Integer imageId = (Integer)dbObject.get("_id");
			imageSuperSet.add(imageId);
		}
		
		List<Integer> orphanImageIds = 
				(List<Integer>)CollectionUtils.subtract(imageSuperSet, imageIdsInAlbums);
		
		for (Integer id : orphanImageIds) {
			query = new BasicDBObject("_id", id.intValue());
			images.remove(query);
		}
	}

}
